package com.android.meige.activity.mine;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;

import com.android.meige.R;
import com.android.meige.app.BaseActivity;
import com.android.meige.model.group.CityChooseData;
import com.android.meige.model.member.LoginResultData;
import com.android.meige.model.member.LoginResultDataCallback;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.MyLog;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.dialog.MainMsg;
import com.elbbbird.android.socialsdk.SocialSDK;
import com.elbbbird.android.socialsdk.model.SocialToken;
import com.elbbbird.android.socialsdk.model.SocialUser;
import com.elbbbird.android.socialsdk.otto.SSOBusEvent;
import com.squareup.otto.Subscribe;
import com.tencent.connect.common.Constants;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class LoginActivity extends BaseActivity {


    public static LoginActivity intance = null;


    @BindView(R.id.progress_loading)
    FrameLayout progress;


    private LoginActivity mcontext;

    private boolean networkConnected;
    private MainMsg mainMsg;
    private ArrayList<String> pin = new ArrayList<String>();
    private ArrayList<CityChooseData.DataBean.Hot_ListBean> hot_list =new ArrayList<>();
    private ArrayList<CityChooseData.DataBean.PinList> pinLists = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        intance = this;
        mcontext = LoginActivity.this;
        ButterKnife.bind(this);

        initUI();

    }

    private void initUI() {
        mainMsg = new MainMsg(mcontext);
        mainMsg.setOnSetLoginStyleClickListener(new MainMsg.OnLoginStyleClickListener() {
            @Override
            public void LoginPhone() {
                startActivity(new Intent(mcontext, SignActivity.class));
                mainMsg.close();
            }

            @Override
            public void LoginQQ() {
                progress.setVisibility(View.VISIBLE);
                SocialSDK.setDebugMode(true);
                SocialSDK.initQQ(ConstantsUrl.QQ_APPID);
                SocialSDK.oauthQQ(mcontext);

            }

            @Override
            public void LoginSina() {
                progress.setVisibility(View.VISIBLE);
                SocialSDK.setDebugMode(true);
                SocialSDK.initWeibo(ConstantsUrl.SINA_WB_APPKEY);
                SocialSDK.oauthWeibo(mcontext);

            }
        });
    }

    @Subscribe
    public void onOauthResult(SSOBusEvent event) {
        switch (event.getType()) {
            case SSOBusEvent.TYPE_GET_TOKEN:
                mainMsg.close();
                progress.setVisibility(View.GONE);
                SocialToken token = event.getToken();
                MyLog.e("登录成功", "获取openid " + token.getOpenId());

                break;
            case SSOBusEvent.TYPE_GET_USER:
                mainMsg.close();
                progress.setVisibility(View.GONE);
                SocialUser user = event.getUser();
                MyLog.e("登录成功", "获取getUnionid " + user.getUnionid());
                MyLog.e("登录成功", "获取头像 " + user.getAvatar());
                setLoginThree(user.getToken().getOpenId(), user.getType(), user.getName(), user.getAvatar(), user.getUnionid());
                break;
            case SSOBusEvent.TYPE_FAILURE:
                mainMsg.close();
                progress.setVisibility(View.GONE);
                Exception e = event.getException();
                MyLog.e("登录失败", "登录失败" + e.toString());
                break;
            case SSOBusEvent.TYPE_CANCEL:
                mainMsg.close();
                progress.setVisibility(View.GONE);
                MyLog.e("取消登录", "取消登录");
                break;
        }
    }


    //登录
    private void setLoginThree(String openid, final int type, String nickname, String avatar, String unionid) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSENDTHREELOGIN;
        HashMap<String, String> map = new HashMap<>();
        String typename = "";
        switch (type) {
            case 1:
                typename = "wb";
                break;
            case 2:
                typename = "wx";
                break;
            case 3:
                typename = "qq";
                break;

        }
        map.put("openid", openid);
        map.put("type", typename);
        map.put("nickname", nickname);
        map.put("avatar", avatar);
        map.put("unionid", unionid);
        MyLog.e("openid", openid);
        MyLog.e("type", typename);
        MyLog.e("nickname", nickname);
        MyLog.e("unionid", unionid);
        MyLog.e("avatar", avatar);
        if (networkConnected) {

            HttpUtils.post(address, null, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    progress.setVisibility(View.GONE);
                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    progress.setVisibility(View.GONE);
                    if(response == null){
                        return;
                    }
                    if (response.getCode() == 0) {
                        LoginResultData.DataBean data = response.getData();
                        if(data!=null){
                            PostLoginThree(data.getUNAME(), data.getAvatar(), data.getUID(), data.getUPSW(), type, data.getZONE(),data.getCITY());
                        }
                    } else {
                        ObjectUtils.toast(mcontext, response.getMsg());
                    }
                }
            });

        } else {
            progress.setVisibility(View.GONE);
            ObjectUtils.toast(mcontext, "网络连接出错了");
        }
    }

    //登录并保存
    private void PostLoginThree(String uname, String avatar, String uid, String upsw, int type,String zone,String city) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, type);
        edit.putString(ConstantsUrl.USERDATA_ZONE,zone);
        edit.putString(ConstantsUrl.USERDATA_CITY,city);
        edit.commit();
        ObjectUtils.toast(mcontext, "登录成功");
        setResultCode(1);
        LoginActivity.intance.finish();
        finish();
    }


    @Override
    protected void onStart() {
        super.onStart();
        progress.setVisibility(View.GONE);
    }

    @OnClick({R.id.weixin_login, R.id.else_login, R.id.back_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.weixin_login:
                progress.setVisibility(View.VISIBLE);
                SocialSDK.setDebugMode(true);
                SocialSDK.initWeChat(ConstantsUrl.WX_APPID, ConstantsUrl.WX_SERCET);
                SocialSDK.oauthWeChat(mcontext);
                break;
            case R.id.else_login:
                mainMsg.show(mcontext.getWindow().getDecorView(), 6, null);
                break;
            case R.id.back_login:

                finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SocialSDK.oauthWeiboCallback(mcontext, requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_LOGIN || requestCode == Constants.REQUEST_APPBAR) {
            SocialSDK.oauthQQCallback(requestCode, resultCode, data);
        }

    }

    public void setResultCode(int code){
        setResult(code);
    }
}
